#! /usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2, sys, re, os, threading

#dst = "http://10.0.90.2"
dst = "https://10.0.103.1:4100"
def_timeout = 1

retry_time = 3500
threads = 10

global_failcnt = 0
mutex = threading.Lock()



def send_http(dst, retry = None, timeout = 5):
	global mutext, global_failcnt
	
	import urllib2

	mutex.acquire()
	urllib2.socket.setdefaulttimeout(timeout)
	mutex.release()
	failcnt = 0

	for i in range(1, retry):
		sys.stdout.write("[%s] : " % threading.currentThread().getName())
		
		try:
			response = urllib2.urlopen(dst)
		except urllib2.HTTPError, e:
			#print "[+"+ str(i) + "] HTTPError, Error code " + e.code

			sys.stdout.write("- %s time request HTTPError, Error code: %d\n" % (i, e.code))
			
			mutex.acquire()
			global_failcnt += 1
			mutex.release()

			failcnt += 1
			continue
		except urllib2.URLError, e:
			#print "[+"+ str(i) + "] URLError: timeout"
			sys.stdout.write("- %s time request URLError, timeout: %d.\n" % (i, timeout))
			mutex.acquire()
			global_failcnt += 1
			mutex.release()

			failcnt += 1
			continue
		#print "[+"+ str(i) + "] HTTP request success\r"
		sys.stdout.write("- %s time request success.\n" % (i))

	sys.stdout.write("%s : %d HTTP request, failed %d times.\n" % threading.currentThread().getName(), retry, failcnt)	
	#print "Total " + str(retry_time) + " HTTP request, failed [" + str(failcnt) +"] times."


def thread_control(dst, times, timeout):
	child = []
	req_per_thread = times/threads
	print "Total %d HTTP Requests, %d threads, %d requests per thread." % (times, threads, req_per_thread)
	#sys.exit(1)
	for i in range(threads):
		t = threading.Thread(target=send_http,args=(dst, req_per_thread, timeout),name='Thread-%d'% i)
		t.setDaemon(1)
		t.start()
		child.append(t)

	for t in child:
		t.join

	print "All %d threads done, %d HTTP requests sent out, failed %d." % (threads, retry_time, global_failcnt)

if __name__ == "__main__":
	thread_control(dst, retry_time, 1)